#include "headers/AuthClient.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QEventLoop>

AuthClient::AuthClient(QObject *parent) : QObject(parent)
{
    m_manager = new QNetworkAccessManager(this);
    connect(m_manager, &QNetworkAccessManager::finished, this, &AuthClient::onCodeReplyFinished);
    connect(m_manager, &QNetworkAccessManager::finished, this, &AuthClient::onRegisterReplyFinished);
    connect(m_manager, &QNetworkAccessManager::finished, this, &AuthClient::onLoginReplyFinished);
}

void AuthClient::requestVerificationCode(const QString &email)
{
    QNetworkRequest request(QUrl(SERVER_URL + "/send_verification_code"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject data;
    data["email"] = email;
    m_manager->post(request, QJsonDocument(data).toJson());
}

void AuthClient::registerUser(const QString &email, const QString &password, const QString &code)
{
    QNetworkRequest request(QUrl(SERVER_URL + "/register"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject data;
    data["email"] = email;
    data["password"] = password;
    data["verification_code"] = code;
    m_manager->post(request, QJsonDocument(data).toJson());
}

bool AuthClient::loginUser(const QString &email, const QString &password)
{
    QNetworkRequest request(QUrl(SERVER_URL + "/login"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QJsonObject data;
    data["email"] = email;
    data["password"] = password;
    QNetworkReply *reply = m_manager->post(request, QJsonDocument(data).toJson());

    QEventLoop loop;
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    bool success = false;
    if (reply->error() == QNetworkReply::NoError) {
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
        QJsonObject obj = doc.object();
        success = obj["success"].toBool();
        emit loginResult(success, obj["message"].toString());
    } else {
        emit loginResult(false, reply->errorString());
    }
    reply->deleteLater();
    return success;
}

void AuthClient::onCodeReplyFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        emit codeSent(true);
    } else {
        emit codeSent(false);
    }
    reply->deleteLater();
}

void AuthClient::onRegisterReplyFinished(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
        QJsonObject obj = doc.object();
        emit registerResult(obj["success"].toBool(), obj["message"].toString());
    } else {
        emit registerResult(false, reply->errorString());
    }
    reply->deleteLater();
}

void AuthClient::onLoginReplyFinished(QNetworkReply *reply)
{
    reply->deleteLater();
}
